/**
 * Created by liuqingxia on 2016/4/11.
 */

/**
 * 点击数据源选择的插入按钮
 */
function clickSourceInsertBtn(selectDiv, type) {

	$(document)
			.on(
					"click",
					"." + type,
					function() {

						var dataSource = $.trim($(this).parent().find(
								"span.dataSource").html());
						var selectDivId = $.trim($(this).parent().parent()
								.attr("id"));
						var selectDataTableName = $.trim($(this).siblings(
								".dataSource")
								.find("input[name=dataTableName]").val());
						var selectDataSourceId = $.trim($(this).siblings(
								".dataSource").find("input[name=tdbid]").val());
						var selectDataSourceJdbc = $.trim($(this).siblings(
								".dataSource").find("input[name=tdbjdbcurl]")
								.val());
						var dataSourceHtml = ""
								+ "<span class='dataSource-row' style='overflow: hidden'>"
								+ "<button class='removeBtn datasource-use-btn'>删除</button>"
								+ "<span class='dataSource'>"
								+ "&nbsp;"
								+ dataSource
								+ "</span>"
								+ "<span class='choiceDataTableName'><input type='hidden' name='dbname' value='"
								+ selectDataTableName
								+ "' /></span>"
								+ "<span class='choiceDataTableId'><input type='hidden' name='dbid' value='"
								+ selectDataSourceId
								+ "' /></span>"
								+ "<span class='choiceDataTableJdbcUrl'><input type='hidden' name='dbJdbcUrl' value='"
								+ selectDataSourceJdbc
								+ "' /></span>"
								+ "<span >读权重：<input style='width:40px;' name='readWeight' type='number' value='0' min='0'/></span>"
								+ "<span >写权重：<input style='width:40px;' name='writeWeight' type='number' value='0' min='0'/></span>"
								+ "</span>";
						$("#" + selectDiv).css("width", "auto");
						$("#" + selectDiv).append(dataSourceHtml);
					});
}


function selectFunction() {
	$(document).on("click", "#datasourceSelect", function() {
		console.log("hdfd");
		var thisOption = $(this).find("option:selected");
		console.log(thisOption);
		if ($(thisOption).html() == "请选择数据源") {
			return false;
		}
		$(".tddl-atom-dll").show();
	});
}

/**
 * 点击数据源选择的删除按钮
 */
function clickSourceRemoveBtn() {
	$(document).on("click", ".removeBtn", function() {
		$(this).parent().remove();
	});
}

/**
 * 闭包，allDataSourceDiv
 * 
 * @param divId
 * @param findAllUrl
 * @returns {{init: init, getAllDataSources: getAllDataSources}}
 */
function getAllDataSourceDiv(divId, findAllUrl, type) {

	var divId = divId;
	var findAllUrl = findAllUrl;

	/**
	 * 获取所有的数据源列表
	 * 
	 * @returns {Array}
	 */
	function getAllDataSources() {
		var dataSources = [];
		var url = getUrlBySuffix(findAllUrl);
		try {
			$.postHttpSync({}, url, function(json) {
				if (json && json.success) {
					dataSources = json['list'];
				} else {
					console.error("获取数据源数组失败");
				}
			});
		} catch (e) {
			console.error("获取数据源数组失败，" + e.message);
		}
		return dataSources;
	}

	/**
	 * 将dataSource数组与html渲染
	 * 
	 * @param dataSources
	 * @returns {Array}
	 */
	function getDataSourceHtml(dataSources) {
		var dataSourceHtml = [];
		var firstHtml = "<option data-tokens='请选择数据源'>请选择数据源</option>";
		dataSourceHtml.push(firstHtml);
		for (var i = 0; i < dataSources.length; i++) {
			var dataSource = dataSources[i];
			var dataSourceType = dataSource["sourceType"];
			if (!(dataSourceType == "4")) {
				var dataSourceRow = "<option data-tokens='"
						+ dataSourceName(dataSource['userName'],
								dataSource['jdbcUrl'])
						+ "'"
						+ "value='"
						+ dataSourceName(dataSource['userName'],
								dataSource['jdbcUrl'])
						+ "'"
						+ "databaseIp='"
						+ (getJdbc(dataSource['jdbcUrl'])).split(":")[0]
						+ "'"
						+ "databasePort='"
						+ getJdbc(dataSource['jdbcUrl']).split(":")[1]
						+ "'"
						+ "databaseType='"
						+ (dataSource['sourceType'] == "1" ? "mysql" : "oracle")
						+ "'"
						+ "databaseName='"
						+ getDataBaseName(dataSource['jdbcUrl'])
						+ "'"
						+ "databaseId='"
						+ (dataSource['id'])
						+ "'>"
						+ ""
						+ dataSourceName(dataSource['userName'],
								dataSource['jdbcUrl']) + "</option>";

				dataSourceHtml.push(dataSourceRow);
			}

		}
		selectFunction();
		return dataSourceHtml;
	}
	
	function getDataBaseName(dataSourcesUrl) {
		var jdbcUrl = dataSourcesUrl;
		if (jdbcUrl.contains("DESCRIPTION")) {/* oracle的RAC格式 */
			return dataBaseNameFliter(HandleOracleRACName(jdbcUrl));
		}

		var removeQuestMark = jdbcUrl.split("?")[0];
		if (!containsIP(removeQuestMark) && removeQuestMark.contains("@")) {
			// console.log("@===="+dataBaseUrlFliter(removeQuestMark.split("@")[1]));
			return dataBaseNameFliter(removeQuestMark.split("@")[1]);
		}

		if (!containsIP(removeQuestMark)
				&& removeQuestMark.contains("mysql://")) {
			// console.log("mysql===="+removeQuestMark.split("mysql://")[1]);
			return dataBaseNameFliter(removeQuestMark.split("mysql://")[1]);
		}

		var ipPortDbReg = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,6}(\/|\:)\w+/;

		var ipPortDb = $.trim(ipPortDbReg.exec(removeQuestMark)).split(",")[0];
		return dataBaseNameFliter(ipPortDb);
	}

	function dataBaseNameFliter(ipPortDBName) {
		if (ipPortDBName.contains("/")) {
			return ipPortDBName.split("/")[1];
		} else {
			var ipPortDBNames = ipPortDBName.split(":");
			return ipPortDBName.split(":")[(ipPortDBNames.length - 1)];
		}
	}

	function getJdbc(dataSourcesUrl) {
		var jdbcUrl = dataSourcesUrl;
		if (jdbcUrl.contains("DESCRIPTION")) {/* oracle的RAC格式 */
			return dataBaseUrlFliter(HandleOracleRACName(jdbcUrl));
		}

		var removeQuestMark = jdbcUrl.split("?")[0];
		if (!containsIP(removeQuestMark) && removeQuestMark.contains("@")) {
			// console.log("@===="+dataBaseUrlFliter(removeQuestMark.split("@")[1]));
			return dataBaseUrlFliter(removeQuestMark.split("@")[1]);
		}

		if (!containsIP(removeQuestMark)
				&& removeQuestMark.contains("mysql://")) {
			// console.log("mysql===="+removeQuestMark.split("mysql://")[1]);
			return dataBaseUrlFliter(removeQuestMark.split("mysql://")[1]);
		}

		var ipPortDbReg = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,6}(\/|\:)\w+/;

		var ipPortDb = $.trim(ipPortDbReg.exec(removeQuestMark)).split(",")[0];
		return dataBaseUrlFliter(ipPortDb);
	}
	function dataBaseUrlFliter(ipPortDBName) {
		if (ipPortDBName.contains("/")) {
			return ipPortDBName.split("/")[0];
		} else {
			return ipPortDBName.substring(0, ipPortDBName.lastIndexOf(":"));
		}
	}

	/**
	 * 初始化allDataSourceDiv
	 */
	function init() {
		var dataSources = getAllDataSources();
		var dataSourceHtml = getDataSourceHtml(dataSources);

		var allDataSourceDiv = $("#" + divId);
		allDataSourceDiv.empty();
		for ( var i in dataSourceHtml) {
			allDataSourceDiv.append(dataSourceHtml[i]);
		}
		$(allDataSourceDiv).selectpicker('refresh');
	}
	
	return {
		init : init,
		getAllDataSources : getAllDataSources
	};

}
